// JavaScript Document
/* PROJECT : Web Cliente Plus
*	@require MyClass.js
*			 MenuSection.js
*			 MyAjax.js
*	         MyBoundingHandler.js
*	@autor: Mauricio Sanchez
*	@create: 02-12-2009
*
*	Dados un punto de evento (que puede ser fijo o movil) y un punto de movil asignado, esta clase va graficando y actualizando las posiciones de los dos
*	puntos en cuestion, permitiendo calcular mediante Gmap Pedometer la mejor ruta entre los dos puntos.
*
*/
//HEREDA DE 'MenuSection'
MenuGetRoad = new MyClass({
	CLASS_NAME: "MenuGetRoad",
	VERSION_NUMBER: "v 1.0.0",			
	 
	 /**  
     * Propertyes: Definicion de properties de configuracion general.
     */	 
     desde: null, //{String} - Identificador de la tabla de cuentas (ABMAcodigos)
	 hasta: null, //{String} - Identificador de la tabla de cuentas (ABMAcodigos)
	 //map: null, //{GMap3} Mapa de googleMaps.
	 	 
	 /**  
     * Propertyes: flags y variables generales
     */	 	 	
	 _dirService : null, //{DirectionsService} Objeto de GMAPS, utilizado para buscar los mejores caminos. 
	 _miniMenu : null, //{MiniMenu}	
	 _infoRecorridoDIV: null,
	 _infoPasosDIV: null,
	 _polyline: null,
	 _steps: null,
	 _stepIcon: null,
	 _flagAutoRefresh:false,
	 	 	 	 
	 /** 
     * Method: init
     */
	 init: function(opciones){
		this.parent(opciones);	
		this.name = "menuGetRoad";		
		this.title = "Recorrido sugerido";
		var me = this;
		this._dirService = new GDirections();//, document.getElementById("directions"));
		GEvent.addListener(this._dirService, "load", function(){ me._onDirectionsLoad();});
        GEvent.addListener(this._dirService, "error", function(){ me._onDirectionsLoadError();});
		this._steps = new Array();		
		this._stepIcon = new GIcon(); 
   		this._stepIcon.image = 'images/markers/MyMarkerStep.png';
		this._stepIcon.iconSize = new GSize(25, 25);
	    this._stepIcon.iconAnchor = new GPoint(12, 25);
	    this._stepIcon.infoWindowAnchor = new GPoint(12, 0);
		//create MiniMenu.
		this._container.className = 'MiniMenu';
		this._miniMenu = new MiniMenu({
									  	name: 'MiniMenu_'+this.name,
										container: this._container
									  });
		this._miniMenu.addButton({ classButton: 'back',
								   onClickFunction: function(){me._goToMenuInfoGral();},
					   			   info: 'Ir a la seccion informacion general'
					 			});	
		this._miniMenu.addButton({ classButton: 'recorrido',
								   onClickFunction: function(){me._generateRecorrido();},
					   			   info: 'Recalcular el recorrido'
					 			});	
		this._miniMenu.addButton({
								   classButton: 'autoRecorrido',
								   classOnClick: 'autoRecorridoActive',
								   onClickFunction: function(){me._flagAutoRefresh = !me._flagAutoRefresh;},
								   info: 'Activar/Desactivar recorrido automatico'
								 });
		this._miniMenu.addButton({ classButton: 'print',
								   onClickFunction: function(){me._printRecorrido();},

					   			   info: 'Imprimir este recorrido'
					 			});	
		
		this.onShow = function(){this._generateRecorrido();};
	 },
	
	 _goToMenuInfoGral: function(){
		  this.sectionContent.viewSection('menuInfoGral');	  			  
	 },
	 
	 
	 _onDirectionsLoad: function(){
		 if (this._dirService.getStatus().code == G_GEO_SUCCESS){			 
			 var mapBounds = this._dirService.getBounds();
			 this.sectionContent._map.setCenter(mapBounds.getCenter(),this.sectionContent._map.getBoundsZoomLevel(mapBounds));
			 var ruta = this._dirService.getRoute(0);			 
		 	 for (var i=0; i<ruta.getNumSteps(); i++){
			 	var step = ruta.getStep(i);
				var myStep = new Object();
				myStep.point = step.getLatLng();
				myStep.html = step.getDescriptionHtml();
				if (i>0){
					myStep.marker = new GMarker (myStep.point, {
											   					icon: this._stepIcon,
																title:"Marca del paso "+(i+1),
									  							zIndex: 10
											   			  		}
												);
					GEvent.addListener(myStep.marker , "click", function() {this.showMapBlowup({zoomLevel:16});});
					this.sectionContent._map.addOverlay(myStep.marker);
				}
				this._steps.push(myStep);			 
		 	 }	
			 
			 this._polyline = this._dirService.getPolyline();
			 var polylineStyle = {color:"#800000",
								  weight: 6,
								  opacity:0.5
								  };
			 this._polyline.setStrokeStyle(polylineStyle);
		 	 this.sectionContent._map.addOverlay(this._polyline); 
			 this._createInfoRecorrido();
			 this._createInfoPasos();			 
		 }		 
		 this.sectionContent.activateBussyImg(false);	
	 },
	 
	 _onDirectionsLoadError: function(){
		 var menuMensaje = this.sectionContent.getSection('menuMessage');
		 menuMensaje.setErrorMessage('No se puede conectar con el servidor de direcciones Google, por favor intente ingresar en otro momento.', 'menuInfoGral');
		 this.sectionContent.viewSection('menuMessage');
		 this.sectionContent.activateBussyImg(false); 
	 },
	 
	 _generateRecorrido: function(){
		 this.sectionContent.activateBussyImg(true); 
		 this._removeRecorrido();
		 var me = this;
		 lat = this.sectionContent.movil.lastLat.toString().substr(0,10);
		 lon = this.sectionContent.movil.lastLon.toString().substr(0,10);
		 var posiMovil  = new GLatLng(lat,lon);
		 var lat = this.sectionContent.cuenta.lastLat.toString().substr(0,10);
		 var lon = this.sectionContent.cuenta.lastLon.toString().substr(0,10);
		 var posiCuenta = new GLatLng(lat,lon);		  
		 var fromTo = new Array(posiMovil, posiCuenta);
		 this._dirService.loadFromWaypoints (fromTo, { "locale": 'es', getPolyline: true, getSteps: true, travelMode: G_TRAVEL_MODE_DRIVING});		 
	 },
	 
	 _createInfoRecorrido:function(){
		 var recorridoFieldSet = document.createElement('fieldset');
		 var legend = document.createElement('legend');
		 legend.innerHTML = "Informacion del recorrido";
		 recorridoFieldSet.appendChild(legend);		 
		 this._infoRecorridoDIV = document.createElement('div');
		 this._infoRecorridoDIV.className = 'infoDiv';	
		 this._infoRecorridoDIV.innerHTML = this.getDataTableRecorrido();
		 recorridoFieldSet.appendChild(this._infoRecorridoDIV);
		 this._miniMenu.append(recorridoFieldSet);
	  },
	  
	  _createInfoPasos:function(){
		 var pasosFieldSet = document.createElement('fieldset');
		 var legend = document.createElement('legend');
		 legend.innerHTML = "Detalle";
		 pasosFieldSet.appendChild(legend);		 
		 this._infoPasosDIV = document.createElement('div');
		 this._infoPasosDIV.className = 'infoDiv';	
		 this._infoPasosDIV.appendChild(this.getDataTablePasosDOM());
		 pasosFieldSet.appendChild(this._infoPasosDIV);
		 this._miniMenu.append(pasosFieldSet);
	  },
	  
	 getDataTableRecorrido: function(){
		  var getRow = function(label,value){
			  			  var response = "<tr>";
		  				  response += " <td width='110' class='label'>";
						  response += label;
						  response += " </td>";
						  response += " <td class='field'>";
						  response += value;
						  response += " </td>";
						  response += "</tr>";
						  return (response);
		  			   }
		  var table = "<table>";
		  
		  var ruta = this._dirService.getRoute(0);
		  table += getRow('Distancia:',ruta.getDistance().html);
		  table += getRow('Tiempo estimado:',ruta.getDuration().html);		  
		  table += "</table>";
		  return table;
	  },
	  
	  getDataTablePasos: function(){
		  var mouseOverTr = function(id){
		  }
		  var getRow = function(label,value,id){
			  			  var response = '<tr onMouseOver="this.style.background=\'#F8FFF8\';" onMouseOut="this.style.background=\'transparent\';">';
		  				  response += " <td valign='top' width='20' class='label'>";
						  response += label;
						  response += " </td>";
						  response += " <td class='field'>";
						  response += value;
						  response += " </td>";
						  response += "</tr>";
						  return (response);
		  			   }
		  var table = "<table>";
		  
		  for (var i=0; i<this._steps.length; i++){
			  table += getRow(i+1+':',this._steps[i].html);
		  }  
		  table += "</table>";
		  return table;
	  },
	  
	  getDataTablePasosDOM: function(){
		  var mouseOverTr = function(id){
		  }
		  var getRow = function(label,step, pos){
			  			  var tr = document.createElement('tr');
			  			  var td1 = document.createElement('td');
			  			  td1.className = 'label';
			  			  td1.width = '20';
			  			  td1.valign = 'top';
			  			  td1.innerHTML = label;
			  			  tr.appendChild(td1);
			  			  
			  			  var td2 = document.createElement('td');
			  			  td2.className = 'field';
			  			  td2.innerHTML = step.html;
			  			  tr.appendChild(td2);
			  			  
			  			  if (pos != 0) {
			  			  	tr.onmouseover = function () { this.style.background='#F8FFF8';};
				  			tr.onmouseout  = function () { this.style.background='transparent';};
			  			  	tr.style.cursor = 'pointer';
			  			  	tr.onclick = function () { step.marker.showMapBlowup({zoomLevel:16}); };
			  			  }
			  			  
			  			  return tr;
		  			   }

		  var table = document.createElement('table');
		  var tbody = document.createElement('tbody');
		  table.appendChild(tbody);
		  
		  for (var i=0; i<this._steps.length; i++){
			  tbody.appendChild(getRow(i+1+':',this._steps[i], i));
		  }  
		  return table;
	  },
	  
	  _removeRecorrido: function(){		  
		  this._miniMenu._content.innerHTML = "";
		  if (this._polyline != null){
			  this.sectionContent._map.removeOverlay(this._polyline);
			  this._polyline = null;
			  for (var i=1; i<this._steps.length; i++){
				  this.sectionContent._map.removeOverlay(this._steps[i].marker);
			  }
			  this._steps = new Array();
		  }
	  },
	  
	  _generatePrintFormatHTML: function(){
		  var includeHTML = '<link href="css/GMapTracing.css" rel="stylesheet" type="text/css" />';
		  var HTML = includeHTML;
		  HTML += '<div class="printFormat">';
		  var tituloHTML = '<span class="title">Reporte general de asignacion de movil a evento</span><br>';
		  HTML += tituloHTML;	
		  HTML += "<br>";
		  var subtituloEvento = '<span class="subtitle">Evento</span><br>';		  
		  HTML += subtituloEvento;
		  HTML += this.sectionContent.getSection('menuInfoGral').getDataTableEvento();
  	      HTML += "<br>";
		  var subtituloMovil = '<span class="subtitle">Movil asignado</span><br>';		  
		  HTML += subtituloMovil;
		  HTML += this.sectionContent.getSection('menuInfoGral').getDataTableMovil();		  
		  var subtituloInfoRecorrido = '<span class="subtitle">Informacion del recorrido</span><br>';
	      HTML += "<br>";
		  HTML += subtituloInfoRecorrido;
		  HTML += this.getDataTableRecorrido();
		  HTML += "<br>";
		  var subtituloPasos = '<span class="subtitle">Detalle de recorrido sugerido</span><br>';		  
		  HTML += subtituloPasos;
		  HTML += this.getDataTablePasos();
		  HTML += '</div>';
		  return HTML;		  
	  },
	  
	  _printRecorrido: function(){
		  var content = this._generatePrintFormatHTML();
		  var pwin=window.open('','print_content','width=820,height=600');
		  pwin.focus();
		  pwin.document.open();
		  pwin.document.write('<html><body onload="window.print()">'+content+'</body></html>');
		  pwin.document.close(); 
		  
		 // setTimeout(function(){pwin.close();},1000);		  
	  },
	  
	  refreshInfo: function(){
		  if (this._flagAutoRefresh){
			  this._generateRecorrido();
		  }
	  }
				
}, MenuSection);